#!/usr/bin/env python3
"""
Example script showing how Claude Code Router with qwen-long configuration works

This demonstrates the token-based routing logic:
- Small requests (≤8K tokens) → Ark model
- Large requests (8K-16K tokens) → qwen-long model  
- Very large requests (>16K tokens) → Refused with warning
"""

import os
from openai import OpenAI

def estimate_tokens(text):
    """Simple token estimation (approximation)"""
    if not text:
        return 0
    english_chars = sum(1 for c in text if c.isalnum() or c.isspace() or c in '.,!?;:-\'\"()[]{}')
    other_chars = len(text) - english_chars
    return int(english_chars / 4 + other_chars / 1.5)

def create_test_content(target_tokens):
    """Create test content with approximately target_tokens"""
    # Average ~4 chars per token for mixed content
    target_chars = target_tokens * 4
    base_text = "This is a test document for Claude Code Router. " * (target_chars // 48 + 1)
    return base_text[:target_chars]

def test_claude_code_router():
    """Test different token sizes with Claude Code Router"""
    
    # This would normally be routed through Claude Code Router (ccr code)
    # For demonstration, we show the logic
    
    test_cases = [
        ("Small Request", 2000),   # Should use Ark model
        ("Medium Request", 6000),  # Should use Ark model
        ("Large Request", 10000),  # Should use qwen-long
        ("Very Large Request", 18000)  # Should be refused
    ]
    
    for case_name, token_count in test_cases:
        print(f"\n{'='*50}")
        print(f"Test Case: {case_name}")
        print(f"Target Tokens: {token_count}")
        print(f"{'='*50}")
        
        # Create test content
        content = create_test_content(token_count)
        actual_tokens = estimate_tokens(content)
        
        print(f"Actual Tokens: {actual_tokens}")
        
        # Simulate routing decision
        if actual_tokens <= 8000:
            print("✓ Routing Decision: Use Ark model (cost-effective)")
            print("  Provider: ark")
            print("  Model: ep-20250723175119-wg4j7")
        elif actual_tokens <= 16000:
            print("✓ Routing Decision: Use qwen-long model (long-context)")
            print("  Provider: dashscope")
            print("  Model: qwen-long")
            print("  Reason: Large context detected")
        else:
            print("❌ Routing Decision: Request REFUSED")
            print("  Reason: Token count exceeds 16K limit")
            print("  Warning: Input token count exceeds maximum limit")
            
        # Show what the actual API call would look like
        if actual_tokens <= 16000:
            messages = [
                {'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': content[:100] + '...' if len(content) > 100 else content}
            ]
            
            if actual_tokens > 8000:
                print("\n  API Configuration for qwen-long:")
                print("  {")
                print(f'    "model": "qwen-long",')
                print(f'    "stream": true,')
                print(f'    "stream_options": {{"include_usage": true}},')
                print(f'    "max_tokens": 8192,')
                print(f'    "temperature": 0.7')
                print("  }")
            else:
                print("\n  API Configuration for Ark:")
                print("  {")
                print(f'    "model": "ep-20250723175119-wg4j7",')
                print(f'    "stream": true,')
                print(f'    "max_tokens": 8192')
                print("  }")

def show_configuration_summary():
    """Show the configuration summary"""
    print("Claude Code Router Configuration Summary")
    print("="*60)
    print()
    print("Token-Based Routing Rules:")
    print("  📊 0 - 8,000 tokens   → Ark Model (cost-effective)")
    print("  📈 8,001 - 16,000 tokens → qwen-long (long-context)")  
    print("  🚫 > 16,000 tokens     → Request refused (cost protection)")
    print()
    print("Providers Configured:")
    print("  🏗️  Ark (Volcengine): ep-20250723175119-wg4j7")
    print("  🔍 DashScope: qwen-long")
    print()
    print("Files Required:")
    print("  📄 ~/.claude-code-router/config.json")
    print("  🔀 ~/.claude-code-router/custom-router.js") 
    print("  🔧 ~/.claude-code-router/plugins/qwen-long-transformer.js")
    print()

if __name__ == "__main__":
    show_configuration_summary()
    test_claude_code_router()
    
    print("\n" + "="*60)
    print("To use this configuration:")
    print("1. Copy the configuration files to ~/.claude-code-router/")
    print("2. Replace API keys with your actual keys")
    print("3. Run: ccr start")
    print("4. Run: ccr code")
    print("5. Test with different sized inputs to see routing in action!")
